package com.lgqz.topsports.fragment;


import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.lgqz.topsports.BR;
import com.lgqz.topsports.R;
import com.lgqz.topsports.adapter.CommentRecyclerAdapter;
import com.lgqz.topsports.adapter.MatchCommentRecyclerAdapter;
import com.lgqz.topsports.bean.MatchContestEntity;
import com.lgqz.topsports.bean.MatchContestShell;
import com.lgqz.topsports.bean.MatchDataEntity;
import com.lgqz.topsports.bean.MatchEntity;
import com.lgqz.topsports.databinding.FragmentEventBinding;
import com.lgqz.topsports.databinding.TimeItemBinding;
import com.lgqz.topsports.util.HttpService;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 */
public class EventFragment extends Fragment implements Callback<MatchDataEntity<MatchEntity>>, SwipeRefreshLayout.OnRefreshListener {


    private Calendar calender;
    private HttpService service;
    private static final SimpleDateFormat NewSDF = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private MatchCommentRecyclerAdapter<Object> adapter;
    private FragmentEventBinding binding;
    private TimeItemBinding group;

    public EventFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_event, container, false).getRoot();
        binding = DataBindingUtil.bind(view);

        calender = Calendar.getInstance();
        group = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.time_item, container, false);
        //下载数据
        initData();

        return view;
    }

    /**
     * 下载比赛页面的数据
     */
    private void initData() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
                    private final SimpleDateFormat SDF =
                            new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);

                    @Override
                    public void write(JsonWriter out, Date value) throws IOException {
                        if (value == null) {
                            out.nullValue();
                        } else {
                            out.value(SDF.format(value));
                        }

                    }

                    @Override
                    public Date read(JsonReader in) throws IOException {
                        if (in.hasNext()) {
                            String s = in.nextString();
                            try {
                                return SDF.parse(s);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }

                        return null;
                    }
                }).create();
        service = new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
                .create(HttpService.class);
        service.getMatch(NewSDF.format(calender.getTime()), NewSDF.format(calender.getTime()))
                .enqueue(this);
        //Log.i("1620", "日期的格式 "+NewSDF.format(calender.getTime()));
        Map<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(Date.class, Pair.create(R.layout.time_item, BR.start));
        map.put(MatchContestEntity.class, Pair.create(R.layout.contest_item, BR.contest));
        adapter = new MatchCommentRecyclerAdapter<>(getContext(), new ArrayList<>(), map);
        //绑定
        binding.matchList.setAdapter(adapter);
        binding.swipe.setOnRefreshListener(this);
        binding.fragmentEvent.addView(group.getRoot());
        //给recyclerview添加滚动监听
        binding.matchList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                View view = recyclerView.getChildAt(0);
                int position = recyclerView.getChildAdapterPosition(view);
                for (int i = position; i >= 0; i--) {

                    Object item = adapter.getItem(i);
                    if (item instanceof Date) {
                        group.setStart((Date) item);
                        break;
                    }
                }
                for (int i = 1; i < recyclerView.getChildCount(); i++) {
                    View childAt = recyclerView.getChildAt(i);
                    if (childAt.getTop() > group.getRoot().getHeight()) {
                        ViewCompat.setTranslationY(group.getRoot(),0);
                        break;
                    }
                    int p = recyclerView.getChildAdapterPosition(childAt);
                    if (adapter.getItemViewType(p) == R.layout.time_item) {
                        ViewCompat.setTranslationY(group.getRoot(),
                                childAt.getTop() - group.getRoot().getHeight());
                        break;
                    }
                }
            }
        });
    }


    @Override
    public void onResponse(Call<MatchDataEntity<MatchEntity>> call, Response<MatchDataEntity<MatchEntity>> response) {
        MatchEntity data = response.body().getData();
//        adapter.add(data.getStart_time());
//        for (MatchContestShell matchContestShell : data.getContest_list()) {
//            adapter.add(matchContestShell.getContest());
//
//        }
        /**
         * 逆向加载数据，让数据每次刷新都显示在上面
         */
        for (int i = data.getContest_list().size() - 1; i >= 0; i--) {
            adapter.add(0, data.getContest_list().get(i).getContest());

        }
        adapter.add(0, data.getStart_time());
        binding.swipe.setRefreshing(false);
        //    Log.i("1620", "熟悉局 "+(data==null));
        //Log.i("1620", "数据下载成功");
    }

    @Override
    public void onFailure(Call<MatchDataEntity<MatchEntity>> call, Throwable t) {
        t.printStackTrace();
        binding.swipe.setRefreshing(false);
        // Log.i("1620", "数据下载失败"+t.getMessage());
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onRefresh() {
        calender.add(Calendar.DAY_OF_YEAR, -1);
        //重新加载前一天的数据
        service.getMatch(NewSDF.format(calender.getTime()), NewSDF.format(calender.getTime()))
                .enqueue(this);
    }
}
